package cn.datawin.service;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.datawin.bean.Form;
import cn.datawin.bean.page.ReqData;
import cn.datawin.bean.page.RespData;
import cn.datawin.spider.seletor.Html;
import cn.datawin.util.SpiderUtil;

import com.googlecode.jsonplugin.JSONException;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;


@Service
public class CityRuleBaseService extends BaseService{
	
	public void insertRuleBase(Map<String, Object> map) {
		String col="cityrulebase";
		map.put("expression", deserialize(map.get("expression").toString()));
		this.insert(col, map);
	}
	
	public Object getRuleBase(ReqData reqData,Form form,String rulename) throws JSONException {
		BasicDBObject query = new BasicDBObject();
		long count=super.count("cityrulebase", query);
		RespData<List<DBObject>> res=makeRes(form, reqData, count,rulename);
		return res;
	}

	public RespData<List<DBObject>> makeRes(Form form,ReqData reqData,long count,String rulename){
		RespData<List<DBObject>> respData = new RespData<List<DBObject>>();
		//获取条件
		BasicDBObject query = new BasicDBObject();
		if (null!=rulename && !rulename.equals("")) {
			Pattern pattern = Pattern.compile("^.*" + rulename+ ".*$", Pattern.CASE_INSENSITIVE);
			query.put("rulename", pattern);
		}
		if(StringUtils.hasLength(form.getKey())){
			Pattern pattern = Pattern.compile("^.*" + form.getKey()+ ".*$", Pattern.CASE_INSENSITIVE);
			BasicDBObject q1 = new BasicDBObject();
			q1.append("rulename", pattern);
			BasicDBObject q2 = new BasicDBObject();
			q2.append("belone", pattern);
			BasicDBList values = new BasicDBList();
			values.add(q1);values.add(q2);
			query.append("$or",values);
		}
		int start = (reqData.getPage() - 1) * reqData.getRows();
		BasicDBObject sort = null;
		//设置sort
		if(reqData.getSort()!=null){
			sort = new BasicDBObject(reqData.getSort(), sortmap.get(reqData.getOrder())); 
		}
		List<DBObject> rows = super.findList("cityrulebase", query, sort, start, reqData.getRows());
		for (int i = 0; i < rows.size(); i++) {
			if (rows.get(i).get("expression") != null && !rows.get(i).get("expression").equals("")) {
				rows.get(i).put("expression", rows.get(i).get("expression").toString());
			}
		}
		respData.setRows(rows);
		respData.setTotal(count);
		return respData;
	}
	
	public void updateRuleBase(Map<String, Object> map, String id) {
		String col="cityrulebase";
		BasicDBObject query = new BasicDBObject();
		map.put("expression", deserialize(map.get("expression").toString()));
		query.put("_id", new ObjectId(id));
		this.updateMulti(col, query, map);
	}
	
	public void deleteRuleBase(String id) {
		String col="cityrulebase";
		BasicDBObject query = new BasicDBObject();
		query.put("_id", new ObjectId(id));
		this.delete(col, query);
	}
	
	public DBObject findRuleBase(String id) {
		String col="cityrulebase";
		BasicDBObject query = new BasicDBObject();
		query.put("_id", new ObjectId(id));
		return this.findOne(col, query);
	}
	
	public HashMap<String, Object> ruleTest(List<Map<String, String>> expressions,String reshtml){
		HashMap<String, Object> params = new HashMap<String, Object>();
		for (Map<String, String> map : expressions) {
			Html html = new Html(reshtml);
			Set<String> sets = map.keySet();
			String n=map.remove("name");
			Iterator<String> ite = sets.iterator();
			while (ite.hasNext()) {
				String type = ite.next();
				String value = map.get(type);
				Method me = SpiderUtil.getHtmlMethod(type);
				if (ite.hasNext()) {
					 SpiderUtil.invokeMethod(me, html, value);
				}else{
					String result = "";
					if(org.apache.commons.lang.StringUtils.isEmpty(value)){
						result = SpiderUtil.invokeMethod(me, html).toString();
					}else{
						result = SpiderUtil.invokeMethod(me, html, value).toString();
					}
					params.put(n, result);
				}
			}
			map.put("name", n);
		}
		return params;
	}
	
	public void addcityDB(Map<String, Object> params,String col,String type){
		if(type.equals("58")){
			if(params.containsKey("cityname") && params.containsKey("url")){
				String[] citys=params.get("cityname").toString().split(" ");
				String[] urls=params.get("url").toString().split(",");
				if(citys.length==urls.length){
					this.delete(col,"{'type':'"+type+"'}");
					Map<String, String> map=new HashMap<String, String>();
					for (int i = 0; i < urls.length; i++) {
						map.put(citys[i], urls[i]);
					}
					Set<String> set=map.keySet();
					Iterator<String> ite=set.iterator();
					while (ite.hasNext()) {
					  Object o=ite.next();
//					  System.out.println(map.get(o));
					  DBObject dbObject=new BasicDBObject();
					  dbObject.put("type", type);
					  dbObject.put("note", type+"城市");
					  dbObject.put("province", "");
					  dbObject.put("city", o.toString());
					  dbObject.put("url", map.get(o).toString());
					  this.insert(col, dbObject);
					}
				}
			}
		}
	}
}
